/*
 * write.c
 *
 *  Created on: 2009-5-28
 *      Author: root
 */

/* devide data which contains by buf into several
 * pieces,and send one piece and wait for the result
 * before sending another piece until all pieces are
 * sent out.
 */

#include"mysocket.h"
#include"msgtype.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#define MAXDATALEN (BUFLEN-40)

int writetosocket(int sock,char *buf,int buflen){
	msg message;
	sockmsg retmsg;
	int i,j,k,rv,len;
	memset(&message,0,sizeof(msg));
	message.mtype=MSG_USR_WRITE;
	message.pid=getpid();
	message.sock=sock;
	message.msgqid=processqid;
	message.buflen=MAXDATALEN;
	k=buflen/MAXDATALEN;
	for(i=0;i<k;i++){
		for(j=0;j<MAXDATALEN;j++)
			message.buf[j]=*(buf+i*MAXDATALEN+j);
		if((rv=msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT))<0){
				fprintf(stderr,"tcp/ip stack does not work!\n");
				return -1;
		}
		if((rv=msgrcv(processqid,&retmsg,sizeof(sockmsg)-sizeof(long),sock,0))<0){
				fprintf(stderr,"tcp/ip stack does not work!\n");
				return -1;
		}
		if(retmsg.ret==-1){
			return -1;
		}
	}
	message.buflen=buflen-k*MAXDATALEN;
	if(message.buflen!=0){
		for(i=0;i<message.buflen;i++){
			message.buf[i]=*(buf+k*MAXDATALEN+i);
		}
		if((rv=msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT))<0){
				fprintf(stderr,"tcp/ip stack does not work!\n");
				return -1;
		}
		if((rv=msgrcv(processqid,&retmsg,sizeof(sockmsg)-sizeof(long),sock,0))<0){
				fprintf(stderr,"tcp/ip stack does not work!\n");
				return -1;
		}
		if(retmsg.ret==-1){
			return -1;
		}
	}

	return buflen;
}
